package com.blog.data;

import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

public class QueryHelper {

	@Deprecated
	public <T> T query( String sql, Class<T> clz ){
		try{
			QueryRunner run = new QueryRunner(C3p0Helper.getDataSource());
			ResultSetHandler<T> handler = new BeanHandler<T>(clz);
			return run.query(sql, handler);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public <T> T query( String sql, Object[] obj, Class<T> clz ){
		try{
			QueryRunner run = new QueryRunner(C3p0Helper.getDataSource());
			ResultSetHandler<T> handler = new BeanHandler<T>(clz);
			return run.query(sql, handler, obj);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Deprecated
	public <T> List<T> queryList( String sql,Class<T> clz ){
		try{
			QueryRunner run = new QueryRunner(C3p0Helper.getDataSource());
			ResultSetHandler<List<T>> handler = new BeanListHandler<T>(clz);
			return run.query(sql, handler);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}
	
	public <T> List<T> queryList( String sql, Object[] obj, Class<T> clz ){
		try{
			QueryRunner run = new QueryRunner(C3p0Helper.getDataSource());
			ResultSetHandler<List<T>> handler = new BeanListHandler<T>(clz);
			return run.query(sql, handler,obj);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}
	
	public void update( String sql, Object[] obj ) throws SQLException{
		QueryRunner run = new QueryRunner(C3p0Helper.getDataSource());
		run.update(sql, obj);
	}
	
	public <T> T scalar( String sql){
		try{
			QueryRunner run = new QueryRunner(C3p0Helper.getDataSource());
			return run.query(sql, new ScalarHandler<T>(1));
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
